using System;
using System.Runtime.InteropServices;
using System.Text;

namespace RawRestructure.Models.DataStructures;

/// <summary>
/// 序列图像最后保存路径结构体（最终确认）
/// </summary>
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct SequenceLastRawSavePath
{
    /// <summary>
    /// 保存的图片队列起始值
    /// </summary>
    public ushort rawNumStart;

    /// <summary>
    /// 保存的张数
    /// </summary>
    public ushort rawLength;

    /// <summary>
    /// 是否为组保存
    /// </summary>
    [MarshalAs(UnmanagedType.U1)]
    public bool rawPair;

    /// <summary>
    /// 保存的文件夹名称（16字节）
    /// </summary>
    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)]
    public byte[] dirName;

    /// <summary>
    /// 创建SequenceLastRawSavePath实例
    /// </summary>
    public static SequenceLastRawSavePath Create(ushort startIndex, ushort length, bool isPair, string directoryName)
    {
        var result = new SequenceLastRawSavePath
        {
            rawNumStart = startIndex,
            rawLength = length,
            rawPair = isPair,
            dirName = new byte[16]
        };

        var nameBytes = Encoding.UTF8.GetBytes(directoryName);
        var copyLength = Math.Min(nameBytes.Length, 16);
        Array.Copy(nameBytes, result.dirName, copyLength);

        return result;
    }

    /// <summary>
    /// 转换为字节数组（小端序）
    /// </summary>
    public readonly byte[] ToByteArray()
    {
        byte[] result = new byte[21]; // 2 + 2 + 1 + 16 = 21字节
        int offset = 0;
        
        // rawNumStart (ushort, 小端序)
        result[offset++] = (byte)(rawNumStart & 0xFF);
        result[offset++] = (byte)((rawNumStart >> 8) & 0xFF);
        
        // rawLength (ushort, 小端序)
        result[offset++] = (byte)(rawLength & 0xFF);
        result[offset++] = (byte)((rawLength >> 8) & 0xFF);
        
        // rawPair (bool, 1字节)
        result[offset++] = (byte)(rawPair ? 1 : 0);
        
        // dirName (16字节)
        if (dirName != null)
        {
            Array.Copy(dirName, 0, result, offset, Math.Min(dirName.Length, 16));
        }
        
        return result;
    }
} 